/*
 * @Description: 
 * @Author: zheng yiliang
 * @Date: 2021-03-17 20:15:59
 * @LastEditTime: 2021-06-13 17:47:22
 * @LastEditors: zheng yiliang
 */
var express = require('express');
var router = express.Router();
const mongoose = require('../core/mongodb')
const { Category, Article, WebUser, Users, Comment, Message, Link, Visitlog, Tag } = require('../model')
const { SuccessModel, ErrorModel } = require('../util')
const { PUBLIC_KEY } = require('../util/encrypt')
const { PUBLIC_ERROR_MSG } = require('../core/constant');
const sd = require('silly-datetime')
// const cors = require("cors")
const axios = require('axios')
const urlencode = require('urlencode');
const webLogin = require('../middleware/webLogin');
const loginCheck = require('../middleware/loginCheck');
const visitor = require('../middleware/visitor')
const { decrypted } = require('../util/encrypt') // 密码解密
const bcrypt = require('bcryptjs')

router.get('/init', loginCheck, async function (req, res) {
  const blogCount = await Article.find().countDocuments()
  const messageCount = await Message.find().countDocuments()
  const userCount = await WebUser.find().countDocuments()
  const visitCount = await Visitlog.find({
    create_time: {
      "$gte": new Date(`${sd.format(new Date, 'YYYY-MM-DD')} 00:00:00`),
      "$lte": new Date(`${sd.format(new Date, 'YYYY-MM-DD')} 23:59:59`)
    }
  }).distinct('IP')

  return res.json(new SuccessModel({ blogCount, messageCount, userCount, visitCount: visitCount.length }))
})

router.post('/changePwd', loginCheck, (req, res) => {
  const { oldPwd, newPwd, userId } = req.body
  Users.findById(userId).then(async data => {
    const oPwd = decrypted(oldPwd) // 密码解密
    const nPwd = decrypted(newPwd) // 密码解密
    const isValid = await bcrypt.compare(oPwd, data.user_password) // 解密后的密码和数据库里对比
    console.log(oPwd, nPwd, isValid)
    if (isValid) {
      try {
        const salt = await bcrypt.genSalt(10)
        const newPwd = await bcrypt.hash(nPwd, salt)
        console.log(newPwd)
        Users.findByIdAndUpdate(userId, {
          user_password: newPwd
        }).then(result => {
          return res.json(new SuccessModel('密码修改成功，下次登录生效'))
        })
      } catch (error) {
        return res.json(new ErrorModel(err))
      }
    } else {
      return res.json(new ErrorModel('密码错误'))
    }

  }).catch(err => {
    return res.json(new ErrorModel(err))

  })
  // const pwd = decrypted(oldPwd) // 密码解密
  // const isValid = await bcrypt.compare(pwd, user.user_password) // 解密后的密码和数据库里对比
  // if (isValid) {
  //   const salt = await bcrypt.genSalt(10)
  //   const newPwd = await bcrypt.hash('zyl1315MC', salt)
  // }
})

router.get('/qqUsers', loginCheck, async function (req, res) {
  const { pagenum, pagesize, nickname, dateRange } = req.query
  console.log(req.query)
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 5
  let conditions = {}
  if (nickname) {
    const reg = new RegExp(nickname, 'i')
    conditions.name = { $regex: eval(reg) }
  }
  if (dateRange) conditions.create_time = {
    "$gte": new Date(`${dateRange[0]} 00:00:00`),
    "$lte": new Date(`${dateRange[1]} 23:59:59`)
  }
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  let responseData = {
    count: 0,
    list: [],
  };
  WebUser.countDocuments(conditions, (err, count) => {
    if (err) {
      console.log('Error:' + err)
    } else {
      responseData.count = count
      // 待返回的字段
      let fields = {};
      let options = {
        skip: skip,
        limit: pageSize,
        sort: { create_time: -1 },
      }
      WebUser.find(conditions, fields, options).then(data => {
        responseData.list = data
        return res.json(new SuccessModel(responseData))
      }).catch(err => {
        return res.json(new ErrorModel(err))
      })
    }
  })
})


router.get('/visiLog', loginCheck, async function (req, res) {
  const { pagenum, pagesize, dateRange } = req.query
  console.log(req.query)
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 5
  let conditions = {}
  if (dateRange) conditions.create_time = {
    "$gte": new Date(`${dateRange[0]} 00:00:00`),
    "$lte": new Date(`${dateRange[1]} 23:59:59`)
  }
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  let responseData = {
    count: 0,
    list: [],
  };
  Visitlog.countDocuments(conditions, (err, count) => {
    if (err) {
      console.log('Error:' + err)
    } else {
      responseData.count = count
      // 待返回的字段
      let fields = {};
      let options = {
        skip: skip,
        limit: pageSize,
        sort: { create_time: -1 },
      }
      Visitlog.find(conditions, fields, options).then(data => {
        responseData.list = data
        return res.json(new SuccessModel(responseData))
      }).catch(err => {
        return res.json(new ErrorModel(err))
      })
    }
  })
})

router.get('/getBlogCountByBlogSort', (req, res) => {
  Category.aggregate([
    {
      $lookup: {
        from: 'articles',
        localField: '_id',
        foreignField: 'category',
        as: 'list'
      }
    }
  ], function (err, docs) {
    console.log(err)
    if (err) return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    console.log(docs)
    const countByBlogs = docs.map(item => {
      return {
        blogSortUid: item._id,
        name: item.name,
        value: item.list.length
      }
    })
    return res.json(new SuccessModel(countByBlogs))
  })
})

router.get('/getBlogCountByTag', (req, res) => {
  Tag.aggregate([
    {
      $lookup: {
        from: 'articles',
        localField: '_id',
        foreignField: 'tags',
        as: 'list'
      }
    }
  ], function (err, docs) {
    console.log(err)
    if (err) return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    console.log(docs)
    const tagByBlogs = docs.map(item => {
      return {
        tagUid: item._id,
        name: item.name,
        value: item.list.length
      }
    })
    return res.json(new SuccessModel(tagByBlogs))
  })
})

// console.log(PUBLIC_KEY)
// 给前端送公钥，密码进行加密
router.post('/getPublicKey', function (req, res, next) {
  res.json(new SuccessModel({ PUBLIC_KEY }, '公钥获取成功'))
});


// 博客前台所有 api ---------------------------------------------------------------------
// 获取分类列表
router.get('/categoryQry', async (req, res) => {
  let fields = { _id: 1, name: 1, desc: 1, create_time: 1 } // 待返回的字段
  Category.find({}, fields, (error, result) => {
    if (error) {
      res.json(new ErrorModel(error, PUBLIC_ERROR_MSG))
    } else {
      res.json(new SuccessModel(result, '分类列表获取成功'))
    }
  })
})

// 获取文章列表
router.get('/articlesgory', visitor, async (req, res) => {
  const { pagenum, pagesize, keyword, dateRange, category } = req.query
  console.log(req.query)
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 5
  let conditions = {
    state: 1,
    secret: 0
  }
  if (keyword) {
    const reg = new RegExp(keyword, 'i')
    conditions = {
      $or: [{ title: { $regex: eval(reg) } }, { desc: { $regex: eval(reg) } }]
    }
  }
  if (category) conditions.category = category
  if (dateRange) conditions.create_time = {
    "$gte": new Date(`${dateRange[0]} 00:00:00`),
    "$lte": new Date(`${dateRange[1]} 23:59:59`)
  }
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  let responseData = {
    count: 0,
    list: [],
  };
  Article.countDocuments(conditions, (err, count) => {
    if (err) {
      console.log('Error:' + err);
    } else {
      responseData.count = count;
      // 待返回的字段
      let fields = {
        title: 1,
        author: 1,
        keyword: 1,
        desc: 1,
        img_url: 1,
        tags: 1,
        category: 1,
        comments: 1,
        like_User_id: 1,
        meta: 1,
        create_time: 1,
        secret: 1,
        origin: 1,
        top: 1
        // update_time: 1,
      };
      let options = {
        skip: skip,
        limit: pageSize,
        sort: { create_time: -1 },
      }
      Article.find(conditions, fields, options)
        .populate([
          { path: 'tags' },
          // { path: 'comments' },
          { path: 'category' }
        ])
        .exec((err, doc) => {
          if (err) {
            console.error('Error:' + err)
            // throw error;
          } else {
            responseData.list = doc;
            return res.json(new SuccessModel(responseData, '文章列表获取成功'))
          }
        })
    }
  })
})


// 获取最新文章
router.get('/newArticlesQry', visitor, async (req, res) => {
  const pageNum = 1
  const pageSize = 3
  let conditions = {
    state: 1,
    secret: 0
  }

  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  // 待返回的字段
  let fields = {
    title: 1,
    author: 1,
    img_url: 1,
    // content: 1,
    desc: 1,
    img_url: 1,
    tags: 1,
    category: 1,
    origin: 1,
    comments: 1,
    like_User_id: 1,
    meta: 1,
    create_time: 1,
  };
  let options = {
    skip: skip,
    limit: pageSize,
    sort: { create_time: -1 },
  }
  Article.find(conditions, fields, options)
    .populate([
      { path: 'tags' },
      { path: 'category' }
    ])
    .exec((err, doc) => {
      if (err) {
        console.error('Error:' + err)
      } else {
        return res.json(new SuccessModel(doc, '文章列表获取成功'))
      }
    })
})

// 根据 id 获取文章详情
router.get('/getArticleById', async (req, res) => {
  const { id } = req.query

  if (!id) return res.json(new ErrorModel('文章id不能为空'))
  // 待返回的字段
  let fields = {
    title: 1,
    author: 1,
    keyword: 1,
    content: 1,
    desc: 1,
    img_url: 1,
    tags: 1,
    category: 1,
    comments: 1,
    like_User_id: 1,
    meta: 1,
    create_time: 1,
    update_time: 1,
    id: 1
  };

  Article.findById(id, fields)
    .populate([
      { path: 'tags' },
      { path: 'category' }
    ])
    .exec((err, doc) => {
      if (err) {
        console.error('Error:' + err)
        return res.json(new ErrorModel('文章详情获取失败'))
        // throw error;
      } else {
        doc.meta.views = doc.meta.views + 1;
        Article.findByIdAndUpdate(id, { meta: doc.meta })
          .then(result => {
            return res.json(new SuccessModel(doc, '文章详情获取成功'))
          })
          .catch(err => {
            console.error('err :', err);
            throw err;
          });
      }
    })
})

// 根据 id 获取上一篇或下一篇
router.get('/preAndNext', async (req, res) => {
  const { id } = req.query
  if (!id) return res.json(new ErrorModel('文章id不能为空'))
  // 待返回的字段
  let fields = {
    _id: 1,
    id: 1,
    title: 1
  };
  // const doc = await Article.find({}, fields, { sort: id })

  const pre = await Article.find({ id: { $gt: id } }, fields).sort({ id: 1 }).limit(1)
  const next = await Article.find({ id: { $lt: id } }, fields).sort({ id: -1 }).limit(1);
  // return res.json(new SuccessModel({ doc, pre, next }, '文章详情获取成功'))
  return res.json(new SuccessModel({ pre: pre[0], next: next[0] }, '信息获取成功'))

})

// 获取归档信息
router.get('/archivesQry', visitor, async (req, res) => {
  Article.find({ state: 1, secret: 0 }, { _id: 1, desc: 1, create_time: 1, title: 1 }).then((doc) => {
    let pages = {}
    doc.forEach(item => {
      const index = sd.format(item.create_time, 'YYYY')
      console.log(pages[index])
      if (!pages[index]) {
        pages[index] = []
      }
      pages[index].push(item)
    })
    return res.json(new SuccessModel(pages, '归档信息获取成功'))
  }).catch(err => {
    console.log(err)
  })
})

// 根据 id 获取分类名称
router.get('/categoryById', (req, res) => {
  const { id } = req.query
  if (!id) return res.json(new ErrorModel('分类id不能为空'))

  Category.findById(id, { name: 1 }).then(doc => {
    return res.json(new SuccessModel(doc, '分类获取成功'))
  }).catch(err => {
    console.log(err)
  })
})


// 获取热门文章
router.get('/hotArticlesQry', async (req, res) => {
  const pageNum = 1
  const pageSize = 8
  let conditions = { state: 1, secret: 0 }
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;

  // 待返回的字段
  let fields = {
    title: 1,
    author: 1,
    keyword: 1,
    desc: 1,
    img_url: 1,
    tags: 1,
    category: 1,
    type: 1,
    comments: 1,
    like_User_id: 1,
    meta: 1,
    create_time: 1,
  };
  let options = {
    skip: skip,
    limit: pageSize,
    sort: { 'meta.views': -1 },
  }
  Article.find(conditions, fields, options)
    .populate([
      { path: 'tags' },
      { path: 'category' }
    ])
    .exec((err, doc) => {
      if (err) {
        console.error('err:' + err)
      } else {
        return res.json(new SuccessModel(doc, '热门文章获取成功'))
      }
    })
})



//多处调用，所以还是存个变量吧
var qqAppID = '101950831';
var qqAppkey = 'c9989571f920c59bb160fc943c80bc1d';

router.post('/qq/login', visitor, function (req, res, next) {
  //拿到code
  var code = req.body.code
  const fullPath = req.body.fullPath
  const qqRedirect_uri = `http://zhengyiliang.cn${fullPath || '/article'}`
  const token = req.cookies.access_token
  const opid = req.cookies.openid
  if (token && opid) {
    axios.get('https://graph.qq.com/user/get_user_info?access_token=' + urlencode(token) + '&oauth_consumer_key=' + urlencode(qqAppID) + '&openid=' + urlencode(opid)).then(user => {
      // res.redirect('http://zhengyiliang.cn/article')
      return res.json(new SuccessModel({ user: JSON.stringify(user.data) }))
    })
  } else {
    //获取token
    var getTokenUrl = 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=' + qqAppID + '&client_secret=' + qqAppkey + '&code=' + code + '&redirect_uri=' + qqRedirect_uri;
    // res.send(getTokenUrl);
    axios.get(getTokenUrl).then(response => {
      var access_token = response.data.split('=')[1].split('&')[0]
      var getMeUrl = 'https://graph.qq.com/oauth2.0/me?access_token=' + access_token;
      res.cookie("access_token", access_token, { maxAge: 86400000, httpOnly: true });
      axios.get(getMeUrl).then(meUrl => {
        console.log(meUrl.data)
        var str = meUrl.data
        var jsonStr = str.replace('callback( ', '');
        jsonStr = jsonStr.replace(' );', '');
        jsonStr = JSON.parse(jsonStr);
        var qqOpenid = jsonStr['openid'];
        res.cookie("openid", qqOpenid, { maxAge: 86400000, httpOnly: true });

        var qqClient_id = jsonStr['client_id'];
        axios.get('https://graph.qq.com/user/get_user_info?access_token=' + urlencode(access_token) + '&oauth_consumer_key=' + urlencode(qqAppID) + '&openid=' + urlencode(qqOpenid)).then(user => {
          const userInfo = JSON.parse(JSON.stringify(user.data))
          WebUser.find({ user_id: qqOpenid }).then(res => {
            if (!res.length) {
              const webuser = new WebUser({
                user_id: qqOpenid,
                name: userInfo.nickname,
                type: qqOpenid === '1099AFF3DD0136F3B4E77B303E40C4E2' ? 0 : 1,
                avatar: userInfo.figureurl_qq_1,
                address: {
                  province: userInfo.province,
                  city: userInfo.city
                },
                year: userInfo.year
              })
              webuser.save().then(data => {
                console.log('首次授权用户信息保存成功')
              }).catch(err => {
                console.log('保存失败', err)
              })
            } else {
              WebUser.findByIdAndUpdate(res[0]._id, {
                name: userInfo.nickname,
                type: qqOpenid === '1099AFF3DD0136F3B4E77B303E40C4E2' ? 0 : 1,
                avatar: userInfo.figureurl_qq_1,
                address: {
                  province: userInfo.province,
                  city: userInfo.city
                },
                year: userInfo.year,
                update_time: Date.now()
              }).then(result => {
                console.log('已授权用户更新信息')
              }).catch(err => {
                console.log('已授权用户更新信息失败')
              })
            }
          })
          return res.json(new SuccessModel({ user: JSON.stringify(user.data), fullPath }))

        })
      })
    }).catch(err => {
      return res.json(new ErrorModel('未登录'))
    })
  }


});

router.get('/qq/logout', visitor, (req, res) => {
  res.clearCookie('access_token')
  res.clearCookie('openid')
  return res.json(new SuccessModel('退出成功'))
})


// ------------------ 评论开始 ---------------
router.post('/addComments', visitor, webLogin, (req, res) => {
  console.log('评论', req.body, req.cookies)
  const { article_id, comment } = req.body
  const comments = new Comment({
    article_id,
    comment,
    user_id: req.cookies.openid
  })
  comments.save().then(data => {
    console.log('新增评论', data._id)
    Article.findById(article_id, { meta: 1 }).then(article => {
      article.meta.comments = article.meta.comments + 1;
      Article.findByIdAndUpdate(article_id, {
        meta: article.meta,
        $addToSet: {
          comments: data._id
        }
      })
        .then(result => {
          return res.json(new SuccessModel(data, '评论成功'))
        })
        .catch(err => {
          console.error('err :', err);
          return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
          // throw err;
        });
    })
  })
  // .catch(err => {
  //   return res.json(new ErrorModel(err, '评论失败'))
  // })
})

router.get('/commentsByArticle', (req, res) => {
  const { article_id } = req.query
  if (!article_id) return res.json(new ErrorModel('文章id不能为空'))

  Comment.aggregate([
    {
      $lookup: {
        from: "webusers",
        localField: "user_id",
        foreignField: "user_id",
        as: "user"
      }
    },
    {
      $sort: { create_time: -1 }
    },
    {
      $match: { article_id: mongoose.Types.ObjectId(article_id) }
    }
  ], function (err, docs) {
    if (err) return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    const comments = docs.map(item => {
      return {
        name: item.user[0].name,
        id: item.user_id,
        headImg: item.user[0].avatar,
        comment: item.comment,
        time: item.create_time,
        like: item.likes,
        inputShow: false,
        _id: item._id,
        type: item.user[0].type,
        reply: item.reply ? item.reply.map(ele => {
          return {
            ...ele,
            inputShow: false
          }
        }) : []
      }
    })
    return res.json(new SuccessModel(comments, '评论列表获取成功'))
  })



  //   .then(data => {
  //     return res.json(new SuccessModel(data, '评论列表获取成功'))
  //   }).catch(err => {
  //     return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
  //   })
})

router.post('/replyComments', visitor, webLogin, (req, res) => {
  const item = {
    from: req.body.from,
    fromId: req.cookies.openid,
    fromAvatar: req.body.fromAvatar,
    fromType: req.cookies.openid === '1099AFF3DD0136F3B4E77B303E40C4E2' ? 0 : 1,
    to: req.body.to,
    toId: req.body.toId,
    toType: req.cookies.openid === '1099AFF3DD0136F3B4E77B303E40C4E2' ? 0 : 1,
    toAvatar: req.body.toAvatar,
    comment: req.body.comment,
    // id: new mongoose.Types.ObjectId()
  }
  Comment.findByIdAndUpdate(req.body._id, {
    $addToSet: {
      reply: item
    }
  }).then(data => {
    console.log(data)
    return res.json(new SuccessModel(data, '回复评论成功'))
    console.log('回复评论成功')
  }).catch(err => {
    // return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    console.log(err)
  })
})
// ------------------ 评论结束 ----------------------

router.post('/addMessage', visitor, webLogin, (req, res) => {
  const { comment } = req.body
  const messages = new Message({
    comment,
    user_id: req.cookies.openid
  })
  messages.save().then(data => {
    return res.json(new SuccessModel(data, '留言成功'))
  })

})
router.get('/messages', visitor, (req, res) => {
  const { pagenum, pagesize } = req.query
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 5
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  Message.aggregate([
    {
      $lookup: {
        from: "webusers",
        localField: "user_id",
        foreignField: "user_id",
        as: "user"
      }
    },
    {
      $sort: { create_time: -1 }
    },
    {
      $skip: skip
    },
    {
      $limit: pageSize
    }
  ], function (err, docs) {
    if (err) return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    const messages = docs.map(item => {
      return {
        name: item.user[0].name,
        id: item.user_id,
        headImg: item.user[0].avatar,
        comment: item.comment,
        time: item.create_time,
        like: item.likes,
        inputShow: false,
        address: item.user[0].address,
        _id: item._id,
        type: item.user[0].type,
        reply: item.reply ? item.reply.map(ele => {
          return {
            ...ele,
            inputShow: false
          }
        }) : []
      }
    })
    return res.json(new SuccessModel(messages, '留言板列表获取成功'))
  })
})

router.post('/replyMessage', visitor, webLogin, (req, res) => {
  const item = {
    from: req.body.from,
    fromId: req.cookies.openid,
    fromAvatar: req.body.fromAvatar,
    fromType: req.cookies.openid === '1099AFF3DD0136F3B4E77B303E40C4E2' ? 0 : 1,
    to: req.body.to,
    toId: req.body.toId,
    toType: req.cookies.openid === '1099AFF3DD0136F3B4E77B303E40C4E2' ? 0 : 1,
    toAvatar: req.body.toAvatar,
    comment: req.body.comment,
    // id: new mongoose.Types.ObjectId()
  }
  Message.findByIdAndUpdate(req.body._id, {
    $addToSet: {
      reply: item
    }
  }).then(data => {
    console.log(data)
    return res.json(new SuccessModel(data, '回复评论成功'))
  }).catch(err => {
    // return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    console.log(err)
  })
})

router.get('/links', visitor, (req, res) => {
  const { pagenum, pagesize } = req.query
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 12
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  // 待返回的字段
  let fields = {
    name: 1,
    desc: 1,
    url: 1,
    icon: 1,
    create_time: 1,
  };
  let options = {
    skip: skip,
    limit: pageSize,
    sort: { 'create_time': -1 },
  }
  Link.find({ state: 1 }, fields, options).then(data => {
    return res.json(new SuccessModel(data, '友链获取成功'))
  }).catch(err => {
    console.log(err)
  })
})

router.get('/news', webLogin, (req, res) => {
  const openid = req.cookies.openid
  WebUser.aggregate([
    {
      $lookup: {
        from: "messages",
        localField: "user_id",
        foreignField: "user_id",
        as: "messages"
      }
    },
    {
      $lookup: {
        from: "comments",
        localField: "user_id",
        foreignField: "user_id",
        as: "comments"
      },
    },
    {
      $sort: { create_time: -1 }
    }
  ], function (err, docs) {
    if (err) return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    console.log(docs)
    let responseData = {
      comments: [],
      messages: []
    }
    docs.forEach(x => {
      let comments = x.comments.map(item => {
        return {
          avatar: x.avatar,
          name: x.name,
          ...item,
          reply: item.reply.filter(ele =>
            ele.toId === openid
          )
        }
      })
      comments = comments.filter(item => item.reply.length)
      if (comments.length) {
        responseData.comments.push(...comments)

      }
      let messages = x.messages.map(item => {
        return {
          avatar: x.avatar,
          name: x.name,
          ...item,
          reply: item.reply.filter(ele =>
            ele.toId === openid
          )
        }
      })
      messages = messages.filter(item => item.reply.length)
      if (messages.length) {
        responseData.messages.push(...messages)

      }

    })

    // let responseData = {
    //   comments,
    //   messages
    // }
    return res.json(new SuccessModel(responseData))
  })

})

router.put('/commentsRead', webLogin, (req, res) => {
  const openid = req.cookies.openid
  if (!req.body._id) return res.json(new ErrorModel('参数有误'))
  Comment.updateMany({ _id: req.body._id }, {
    $set: { "reply.$[reply].is_handle": 1 },
    is_handle: 1
  }, { arrayFilters: [{ 'reply.toId': openid }] }).then(data => {
    console.log(data)
    if (data.nModified) {
      return res.json(new SuccessModel('成功一键标记为已读'))
    }
    return res.json(new ErrorModel('一键标记为已读失败'))
  }).catch(err => {

  })
})

router.put('/messagesRead', webLogin, (req, res) => {
  const openid = req.cookies.openid
  if (!req.body._id) return res.json(new ErrorModel('参数有误'))
  Message.updateMany({ _id: req.body._id }, {
    $set: { "reply.$[reply].is_handle": 1 },
    is_handle: 1
  }, { arrayFilters: [{ 'reply.toId': openid }] }).then(data => {
    console.log(data)
    if (data.nModified) {
      return res.json(new SuccessModel('成功一键标记为已读'))
    }
    return res.json(new ErrorModel('一键标记为已读失败'))
  }).catch(err => {

  })
})

router.get('/recentVisitors', (req, res) => {
  // const { pagenum, pagesize } = req.query
  const pageNum = 1
  const pageSize = 12
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  // 待返回的字段
  let fields = {
    name: 1,
    avatar: 1,
  };
  let options = {
    skip: skip,
    limit: pageSize,
    sort: { 'update_time': -1 },
  }
  WebUser.find({}, fields, options).then(data => {
    return res.json(new SuccessModel(data, '最近访客获取成功'))
  }).catch(err => {
    console.log(err)
  })
})

module.exports = router;
